// pages/projectDetails/projectDetails.js
import http from "../../utils/http";
import { 
  getProjectByIdService, 
  increaseProjectViewCountService, 
  joinProjectService 
} from "../../api/project";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    direction: "落地",
    checked: false,
    projectId: null,
    projectDetails: null,
    loading: true,
    hasJoined: false,
    school: {},
    randomProjectIds: [],
    directionOptions: [
      { key: "落地", value: 1 },
      { key: "获奖", value: 2 },
      { key: "学习", value: 3 },
    ],
    loginModalShown: false,
    showModal2: false,
    showOverlay: false,
    status: null,
    pageUrl:"pages/interested/interested",
  },

  /**
   * 显示登录提示 - 替换为使用loginModal组件
   */
  showLoginPrompt() {
    this.setData({
      showModal2: true,
      showOverlay: true,
    });
  },

  /**
   * 处理取消登录事件
   */
  onCancelLogin() {
    this.setData({
      showModal2: false,
      showOverlay: false,
    });
  },

  /**
   * 检查登录状态（不弹窗）
   */
  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    return !!token;
  },

  /**
   * 获取项目详情 - 允许未登录访问，401时提示登录但不强制
   */
  getProjectDetails() {
    if (!this.data.projectId) {
      wx.showToast({
        title: "项目ID不存在",
        icon: "error",
        duration: 2000,
      });
      return;
    }

    this.setData({
      loading: true,
    });

    http
      .get("/project/projectById/" + this.data.projectId)
      .then((res) => {
        const educationRequirement = this.formatEducationRequirement(
          res.data.educationRequirement,
        );
        this.setData({
          projectDetails: res.data,
          educationRequirement,
          direction: this.formatDirection(res.data.direction),
          loading: false,
        });
      })
      .catch((err) => {
        console.error("获取项目详情失败:", err);
        
        // 如果是401错误且用户未登录，友好提示但允许查看部分信息
        if (err.statusCode === 401 && !this.checkLoginStatus()) {
          this.setData({
            loading: false,
          });
          wx.showModal({
            title: "提示",
            content: "登录后可查看完整项目信息",
            confirmText: "去登录",
            cancelText: "暂不登录",
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: "/pages/login/login",
                });
              }
            },
          });
        } else {
          this.handleError("获取项目详情失败");
        }
      });
  },

  /**
   * 格式化跨校字段
   */
  formatCrossSchool(crossSchool) {
    if (crossSchool === 1 || crossSchool === true) {
      return "是";
    } else if (crossSchool === 0 || crossSchool === false) {
      return "否";
    }
    return "未知";
  },

  /**
   * 格式化教育要求字段
   */
  formatEducationRequirement(educationRequirement) {
    const educationMap = {
      1: "大专",
      2: "本科",
      3: "硕士",
      4: "博士",
    };
    return educationMap[educationRequirement] || "未知";
  },

  /**
   * 格式化项目方向字段
   */
  formatDirection(direction) {
    const directionMap = {
      1: "落地",
      2: "获奖",
      3: "学习",
    };
    return directionMap[direction] || "落地";
  },

  /**
   * 处理认证错误
   */
  handleAuthError() {
    this.setData({
      loading: false,
    });

    wx.removeStorageSync("token");
    this.showLoginPrompt();
  },

  /**
   * 统一错误处理
   */
  handleError(message, needLogin = false) {
    this.setData({
      loading: false,
    });

    if (needLogin) {
      this.handleAuthError();
    } else {
      wx.showToast({
        title: message,
        icon: "error",
        duration: 2000,
      });
    }
  },

  /**
   * 获取随机项目列表
   */
  getRandomProjectIds() {
    const params = {
      pageNum: 1,
      pageSize: 50,
    };

    http
      .get("/project/allproject", params)
      .then((res) => {
        console.log("获取项目列表完整响应:", res);

        if (res.statusCode === 200 && res.data) {
          console.log("响应数据结构:", res.data);

          let projectIds = [];

          if (res.data.code === 200) {
            if (Array.isArray(res.data.data)) {
              projectIds = res.data.data
                .map((project) => project.id)
                .filter((id) => id !== this.data.projectId);
            }
            else if (res.data.data && res.data.data.id) {
              projectIds = [res.data.data.id].filter(
                (id) => id !== this.data.projectId,
              );
            }
          }
          else if (Array.isArray(res.data)) {
            projectIds = res.data
              .map((project) => project.id)
              .filter((id) => id !== this.data.projectId);
          }
          else if (res.data.id) {
            projectIds = [res.data.id].filter(
              (id) => id !== this.data.projectId,
            );
          }

          console.log("解析到的项目ID列表:", projectIds);
          console.log("当前项目ID:", this.data.projectId);

          this.setData({
            randomProjectIds: projectIds,
          });

          if (projectIds.length === 0) {
            console.log("没有找到可用的项目ID");
          }
        } else {
          console.log("响应格式不符合预期:", res);
        }
      })
      .catch((err) => {
        console.error("获取项目列表失败:", err);
      });
  },

  /**
   * 跳转到下一条随机项目 - 添加防抖处理
   */
  goToNextProject() {
    // 防抖处理
    if (this.nextProjectTimer) {
      clearTimeout(this.nextProjectTimer);
    }

    this.nextProjectTimer = setTimeout(() => {
      if (this.data.randomProjectIds.length === 0) {
        wx.showLoading({
          title: "获取项目列表...",
        });

        this.getRandomProjectIds();

        setTimeout(() => {
          wx.hideLoading();
          this.performRandomJump();
        }, 1500);
        return;
      }

      this.performRandomJump();
    }, 300);
  },

  /**
   * 执行随机跳转
   */
  performRandomJump() {
    console.log(
      "执行随机跳转，可用项目数量:",
      this.data.randomProjectIds.length,
    );

    if (this.data.randomProjectIds.length === 0) {
      wx.showToast({
        title: "暂无更多项目",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    const randomIndex = Math.floor(
      Math.random() * this.data.randomProjectIds.length,
    );
    const nextProjectId = this.data.randomProjectIds[randomIndex];

    console.log("随机选择的项目ID:", nextProjectId);

    if (nextProjectId) {
      wx.redirectTo({
        url: `/pages/projectDetails/projectDetails?projectId=${nextProjectId}`,
      });
    } else {
      wx.showToast({
        title: "暂无更多项目",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 投递信息/参与项目功能 - 添加登录检查
   */
  joinProject() {
    // 检查登录状态，未登录则弹出登录提示
    if (!this.checkLoginStatus()) {
      this.showLoginPrompt();
      return;
    }

    // 防抖处理
    if (this.joinProjectTimer) {
      clearTimeout(this.joinProjectTimer);
    }

    this.joinProjectTimer = setTimeout(() => {
      if (this.data.hasJoined) {
        wx.showToast({
          title: "您已投递过此项目",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      if (!this.data.projectId) {
        wx.showToast({
          title: "项目ID不存在",
          icon: "error",
          duration: 2000,
        });
        return;
      }

      wx.showModal({
        title: "确认投递",
        content: `确定要投递这个项目吗？选择方向：${this.data.direction}`,
        success: (res) => {
          if (res.confirm) {
            this.submitJoinRequest();
          }
        },
      });
    }, 300);
  },

  submitJoinRequest() {
    wx.showLoading({
      title: "正在投递...",
    });

    console.log("开始投递项目，项目ID:", this.data.projectId);

    this.send().then(() => {
      let requestData = {
        id: this.data.projectId
      };
      
      const statusValue = this.data.status !== null ? this.data.status : false;
      if (statusValue) {
        requestData.status = statusValue;
        requestData.pageUrl = this.data.pageUrl || "pages/interested/interested";
      }

      console.log("投递请求参数:", {
        url: `/project/join/${this.data.projectId}`,
        data: requestData,
        projectId: this.data.projectId,
        status: this.data.status,
        pageUrl: this.data.pageUrl
      });

      http
        .post(`/project/join/${this.data.projectId}`, requestData)
        .then((res) => {
          wx.hideLoading();
          console.log("投递项目响应:", res);

          if (res.code === 200) {
            wx.showToast({
              title: "投递成功",
              icon: "success",
              duration: 2000,
            });

            this.setData({
              hasJoined: true,
            });

            setTimeout(() => {
              this.checkJoinStatus();
            }, 1000);
          } else if (res.code === 401) {
            this.handleAuthError();
          } else {
            const errorMessage = res.message || "投递失败";
            wx.showModal({
              title: "投递失败",
              content: `${errorMessage}`,
              showCancel: false,
              confirmText: "确定",
            });
          }
        })
        .catch((err) => {
          wx.hideLoading();
          console.error("投递项目失败:", err);
          const errorMessage = err.data?.message || "网络错误，请重试";
          wx.showModal({
            title: "投递失败",
            content: `${errorMessage}`,
            showCancel: false,
            confirmText: "确定",
          });
        });
    });
  },

  /**
   * 检查是否已参与项目 - 只在登录时检查
   */
  checkJoinStatus() {
    if (!this.data.projectId || !this.checkLoginStatus()) {
      return;
    }

    http
      .get(`/project/isjoin/${this.data.projectId}`)
      .then((res) => {
        if (res.code === 200 && res.data) {
          if (res.data.code === 200) {
            this.setData({
              hasJoined: res.data.isJoin || false,
            });
          }
        }
      })
      .catch((err) => {
        console.error("检查参与状态失败:", err);
      });
  },

  send() {
    return new Promise((resolve) => {
      wx.requestSubscribeMessage({
        tmplIds: ['XL8H14dm702_U2VqO--zp_IcHkOO7BpYCZ5OPQ4KbnM'],
        success: (res) => {
          console.log('成功', res);
          
          const isAccepted = res['XL8H14dm702_U2VqO--zp_IcHkOO7BpYCZ5OPQ4KbnM'] === 'accept';
          this.setData({
            status: isAccepted
          });
          console.log(this.data.status);
          resolve();
        },
        fail: (res) => {
          console.log('失败', res);
          this.setData({
            status: false
          });
          
          wx.showToast({
            title: '操作取消',
            icon: 'none'
          });
          resolve();
        },
        complete: () => {
          resolve();
        }
      });
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  onShareTimeline(){
    return{
      title:"队伍详情",
      query:'/project/projectById/',
      imageUrl:'https://kuaizu-img-file.oss-cn-hangzhou.aliyuncs.com/kuaizu-img/imges/images/background.jpg'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("页面参数:", options);
    if (options.projectId) {
      this.setData({
        projectId: parseInt(options.projectId),
      });

      // 获取项目详情（无需登录）
      this.getProjectDetails();
      // 如果已登录，检查参与状态
      if (this.checkLoginStatus()) {
        this.checkJoinStatus();
      }
      // 获取随机项目列表
      this.getRandomProjectIds();
    } else {
      wx.showToast({
        title: "项目ID缺失",
        icon: "error",
        duration: 2000,
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.projectId && !this.data.projectDetails) {
      this.getProjectDetails();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log("下拉刷新");
    this.getProjectDetails();
    if (this.checkLoginStatus()) {
      this.checkJoinStatus();
    }
    this.getRandomProjectIds();
    wx.stopPullDownRefresh();
  },

  onReady() {},
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.nextProjectTimer) {
      clearTimeout(this.nextProjectTimer);
    }
    if (this.joinProjectTimer) {
      clearTimeout(this.joinProjectTimer);
    }
    
    this.setData({
      loginModalShown: false,
    });
  },

  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.projectDetails?.projectName || "项目分享",
      path: `/pages/projectDetails/projectDetails?projectId=${this.data.projectId}`,
    };
  },

  onShareTimeline(){
    return {
      title: this.data.projectDetails?.projectName || "项目分享",
      path: `/pages/projectDetails/projectDetails?projectId=${this.data.projectId}`,
      imageUrl:'/images/qqq.png'
    };
  },
});